let db = require('../db/index')

exports.all = (req, res) => {
  var sql = 'select * from info'
  db.query(sql, (err, data) => {
    if (err) {
      return res.send('错误：' + err.message)
    }
    res.send(data)
  })
}

exports.get = (req, res) => {
  var sql = 'select * from info where id = ?'
  db.query(sql, [req.query.id], (err, data) => {
    if (err) {
      return res.send('错误：' + err.message)
    }
    res.send(data)
  })
}

exports.search = (req, res) => {
  var sql = 'select * from info where name like ?'
  db.query(sql, [req.query.name], (err, data) => {
    if (err) {
      return res.send({
        state: 400,
        message: err.message
      })
    }
    res.send(data)
  })
}

exports.del = (req, res) => {
  var sql = 'delete from info where id = ?'
  db.query(sql, [req.query.id], (err, data) => {
    if (err) {
      return res.send('错误：' + err.message)
    }
    if(data.affectedRows > 0) {
      res.send({
        state: 200,
        message: 'success'
      })
    }else{
      res.send({
        state: 202,
        message: 'error'
      })
    }
  })
}

exports.add = (req, res) => {
  var sql = 'insert into info (id,name,address,tel) values (?,?,?,?)'
  db.query(sql, [req.body.id, req.body.name, req.body.address, req.body.tel], (err, data) => {
    if (err) {
      return res.send({
        state: 400,
        message: err.message
      })
    }
    if(data.affectedRows > 0) {
      res.send({
        state: 200,
        message: 'success'
      })
    }else{
      res.send({
        state: 202,
        message: 'error'
      })
    }
  })
}

exports.update = (req, res) => {
  var sql = 'update info set name = ?, address = ?, tel = ? where id = ?'
  db.query(sql, [req.body.name, req.body.address, req.body.tel, req.body.id], (err, data) => {
    if (err) {
      return res.send({
        state: 400,
        message: err.message
      })
    }
    if(data.changedRows > 0) {
      res.send({
        state: 200,
        message: 'success'
      })
    }else{
      res.send({
        state: 202,
        message: 'error',
        data
      })
    }
  })
}
